﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BskLeague.Models;
using System.IO;

namespace BskLeague.Controllers
{
    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
        BskLeagueDB _db = new BskLeagueDB();
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            List<AnnounceCommunicate> communicates = _db.AnnounceCommunicates.Include("Players").Include("Status").ToList();
            return View(communicates);
        }

        public ActionResult CreatePlayer(int id)
        {
            var announcePlayer = _db.AnnouncedPlayers.SingleOrDefault(a => a.AnnouncedPlayerId == id);
            var season = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            if (season == null)
            {
                var maxSeasonId = _db.Seasons.Max(v => v.SeasonId);
                season = _db.Seasons.SingleOrDefault(s => s.SeasonId == maxSeasonId);
            }
            Licence licence = new Licence { SeasonExp = _db.Seasons.ToList()[0] };

            Player player = new Player
            {
                PlayerName = announcePlayer.Name,
                PlayerSurname = announcePlayer.Surname,
                Email = announcePlayer.Email,
                UserName = announcePlayer.Email,
                Licence = licence
            };

            String password = System.Web.Security.Membership.GeneratePassword(16, 2);
            //String password = p.Email;
            RegisterModel user = new RegisterModel
            {
                UserName = announcePlayer.Email,
                Email = announcePlayer.Email,
                Password = password,
                ConfirmPassword = password
            };

            String credentials = player.PlayerName + " " + player.PlayerSurname + " " + "\notrzymał(a) konto w systemie:\nUserName = "
                + user.Email + "\nPassword: " + password + "\n";
            System.Web.Security.MembershipCreateStatus createStatus;
            System.Web.Security.Membership.CreateUser(user.UserName, user.Password, user.Email, null, null, true, null, out createStatus);

            //tu: zapisz to do pdfa, zapisz w App_data/Admin_files
            //zwróć tego pdfa.
            player.Date = new DateTime(1980, 9, 21);

            _db.Licences.Add(licence);
            _db.Players.Add(player);

            announcePlayer.InDatabase = true;
            announcePlayer.Licence = licence;

            _db.SaveChanges();


            string path = Server.MapPath("/PDFs/");
            string fileName=user.Email+"_credentials";
            PdfGenerator.GenerateAccount(fileName, path, "Wrocław, "+DateTime.Now.ToShortDateString().ToString(), "Utworzenie konta w systemie", "Informujemy, że w systemie amatorskiej ligi koszykówki BasketLeague zostało utworzone konto. Dane konieczne do zalogowania zostały zamieszczeone poniżej:", "Login: " + user.Email, "Hasło: " + password);


            fileName += ".pdf";
            return RedirectToAction("FileGenerated", "Files", new{name = fileName });
        }



        public ActionResult Confirm(int id)
        {
            AnnounceCommunicate communicate = _db.AnnounceCommunicates.Include("Players").ToList().Find(c => c.AnnounceCommunicateId == id);
            communicate.ConfirmAnnouncement(_db);

            return RedirectToAction("Index", "Admin");
        }

        public ActionResult PaymentFile(int id)
        {
            var communicate = _db.AnnounceCommunicates.SingleOrDefault(c => c.AnnounceCommunicateId == id);


            return File(Path.Combine(Server.MapPath("~/App_data/uploads"), communicate.PaymentFileName),
            "text/plain",
            communicate.PaymentFileName);
        }

        public ActionResult DeleteAnnouncement(int id)
        {
            var announcement = _db.AnnounceCommunicates.Include("Players").SingleOrDefault(ac => ac.AnnounceCommunicateId == id);
            while (announcement.Players.Count > 0)
            {
                _db.AnnouncedPlayers.Remove(announcement.Players[0]);
            }

            _db.AnnounceCommunicates.Remove(announcement);
            _db.SaveChanges();

            return RedirectToAction("Index", "Admin");
        }

        public ActionResult Communicates()
        {
            var communicates = _db.Communicates.Where(c => c.Receiver == "Admin").OrderByDescending(c => c.Date).ToList();
            return View(communicates);
        }

        public ActionResult CreateCommunicate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateCommunicate(Communicate communicate, string RL)
        {
            string[] users = RL.Split(new char[] { ';' });

            foreach (var u in users)
            {
                var com = new Communicate { Date = DateTime.Now, Receiver = u, Sender = "Admin", Content = communicate.Content };
                _db.Communicates.Add(com);
            }

            _db.SaveChanges();

            return RedirectToAction("Communicates");
        }

        public JsonResult GetAllPlayers()
        {
            List<String> result = new List<string>();
            var actualSeason = _db.Seasons.Single(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                // var players = _db.Players.ToList().FindAll(p => p.STPs.Any(stp => stp.Season == actualSeason));
                var players = _db.Players.Where(p => p.STPs.Any(stp => stp.SeasonId == actualSeason.SeasonId)).ToList();


                foreach (var p in players)
                {
                    result.Add(p.UserName);
                }
            }
            return Json(result);
        }

        public JsonResult GetAllChefs()
        {
            List<string> chefsUsers = new List<string>();
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                var teams = _db.Teams.Where(t => t.STPs.Any(stp => stp.SeasonId == actualSeason.SeasonId)).ToList();

                foreach (var t in teams)
                {
                    chefsUsers.Add(t.ChefPlayer.UserName);
                } 
            }

            return Json(chefsUsers);
        }

        public JsonResult GetChefs()
        {
            List<string> chefsUsers = new List<string>();
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);

            if (actualSeason != null)
            {
                var teams = _db.Teams.Where(t => t.STPs.Any(stp => stp.SeasonId == actualSeason.SeasonId)).ToList();

                foreach (var t in teams)
                {
                    chefsUsers.Add(t.TeamName);
                    chefsUsers.Add(t.ChefPlayer.UserName);
                }
            }

            return Json(chefsUsers); 
        }

        public JsonResult GetPlayers()
        {
            List<string> result = new List<string>();

            var actualSeason = _db.Seasons.Single(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                var players = _db.Players.Where(p => p.STPs.Any(stp => stp.SeasonId == actualSeason.SeasonId)).ToList();



                foreach (var p in players)
                {
                    result.Add(p.PlayerName + " " + p.PlayerSurname);
                    result.Add(p.UserName);
                }
            }

            return Json(result);
        }

        public ActionResult AnnounceDetails(int id)
        {
            var announce = _db.AnnounceCommunicates.Include("Players").SingleOrDefault( a => a.AnnounceCommunicateId == id);
            var recrutationSeason = _db.Seasons.SingleOrDefault(s => s.StatusId == 1);
            if (recrutationSeason == null)
                ViewBag.recrutationSeason = false;
            else
                ViewBag.recrutationSeason = true;

            return View(announce);
        }

        public ActionResult ManageSeasons()
        {
            var seasons = _db.Seasons.ToList();

            return View(seasons);
        }

        public ActionResult MakeRecrutation(int id)
        {
            var seasons = _db.Seasons.ToList();
            foreach (var s in seasons)
            {
                s.Status = _db.SeasonStatuses.SingleOrDefault(st => st.Status == "Finished");
            }

            var season = _db.Seasons.SingleOrDefault(s => s.SeasonId == id);
            season.Status = _db.SeasonStatuses.SingleOrDefault(ss => ss.Status == "Recrutation");

            _db.SaveChanges();

            return RedirectToAction("ManageSeasons");
        }
        public ActionResult MakeActive(int id)
        {
            var seasons = _db.Seasons.ToList();
            foreach (var s in seasons)
            {
                s.Status = _db.SeasonStatuses.SingleOrDefault(st => st.Status == "Finished");
            }

            var season = _db.Seasons.SingleOrDefault(s => s.SeasonId == id);
            season.Status = _db.SeasonStatuses.SingleOrDefault(ss => ss.Status == "Active");
            _db.SaveChanges();

            return RedirectToAction("ManageSeasons");
        }
        public ActionResult MakeFinished(int id)
        {
            var season = _db.Seasons.SingleOrDefault(s => s.SeasonId == id);
            season.Status = _db.SeasonStatuses.SingleOrDefault(ss => ss.Status == "Finished");
            _db.SaveChanges();

            return RedirectToAction("ManageSeasons");
        }

        public ActionResult CreateSeason()
        {
            var seasonStatuses = _db.SeasonStatuses.ToList();
            var items = new List<SelectListItem>();

            foreach (var ss in seasonStatuses)
            {
                items.Add(new SelectListItem { Text=ss.Status, Value=ss.StatusId.ToString()}); 
            }

            ViewBag.Items = items;
            return View();
        }

        [HttpPost]
        public ActionResult CreateSeason(Season season)
        {
            season.Status = _db.SeasonStatuses.SingleOrDefault(s => s.StatusId == season.StatusId);
            if (season.StatusId != 3)
            {
                var seasons = _db.Seasons.ToList();
                foreach (var s in seasons)
                {
                    s.Status = _db.SeasonStatuses.SingleOrDefault(st => st.Status == "Finished");
                }
            }

            _db.Seasons.Add(season);
            _db.SaveChanges();

            return RedirectToAction("ManageSeasons");
        }

        public ActionResult ManageSTP()
        {
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            List<SeasonTeamPlayer> stps = null;
            if (actualSeason != null)
            {
                stps = _db.SeasonTeamPlayers.Include("Player").Include("Team").Where(stp => stp.Season.SeasonId == actualSeason.SeasonId).ToList();
            }
            else
            {
                 stps = new List<SeasonTeamPlayer>();
            }
            return View(stps);
        }

        public ActionResult CreateSTP()
        {
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            var teams = new List<SelectListItem>();
            var players = new List<SelectListItem>();
            var seasons = new List<SelectListItem>();

            foreach (var t in _db.Teams.ToList())
            {
                teams.Add(new SelectListItem { Text = t.TeamName, Value = t.TeamId.ToString() });
            }
            foreach (var p in _db.Players.ToList())
            {
                players.Add(new SelectListItem { Text = p.PlayerName +" "+ p.PlayerSurname, Value = p.PlayerId.ToString() });
            }
            foreach (var s in _db.Seasons.ToList())
            {
                seasons.Add(new SelectListItem { Text = s.SeasonName, Value = s.SeasonId.ToString() });
            }

            ViewBag.Teams = teams;
            ViewBag.Players = players;
            ViewBag.Seasons = seasons;
            if (actualSeason != null)
                return View(new SeasonTeamPlayer { Season = actualSeason, SeasonId = actualSeason.SeasonId });
            else
                return View(new SeasonTeamPlayer());
        }

        [HttpPost]
        public ActionResult CreateSTP(SeasonTeamPlayer stp)
        {
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                stp.Season = actualSeason;
                _db.SeasonTeamPlayers.Add(stp);
                _db.SaveChanges();
            }
            return RedirectToAction("ManageSTP");
        }

        public ActionResult DeleteSTP(int id)
        {
            var stp = _db.SeasonTeamPlayers.SingleOrDefault(s => s.SeasonTeamPlayerId == id);
            _db.SeasonTeamPlayers.Remove(stp);
            _db.SaveChanges();

            return RedirectToAction("ManageSTP");
        }

        public ActionResult EditSTP(int id)
        {
            var stp = _db.SeasonTeamPlayers.SingleOrDefault(s => s.SeasonTeamPlayerId == id);

            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            var teams = new List<SelectListItem>();
            var players = new List<SelectListItem>();
            var seasons = new List<SelectListItem>();

            foreach (var t in _db.Teams.ToList())
            {
                teams.Add(new SelectListItem { Text = t.TeamName, Value = t.TeamId.ToString() });
            }
            foreach (var p in _db.Players.ToList())
            {
                players.Add(new SelectListItem { Text = p.PlayerName +" "+ p.PlayerSurname, Value = p.PlayerId.ToString() });
            }
            foreach (var s in _db.Seasons.ToList())
            {
                seasons.Add(new SelectListItem { Text = s.SeasonName, Value = s.SeasonId.ToString() });
            }

            ViewBag.Teams = teams;
            ViewBag.Players = players;
            ViewBag.Seasons = seasons;

            return View(stp);
        }

        [HttpPost]
        public ActionResult EditSTP(SeasonTeamPlayer stp)
        {
            var dbStp = _db.SeasonTeamPlayers.SingleOrDefault(s => s.SeasonTeamPlayerId == stp.SeasonTeamPlayerId);
            var player = _db.Players.SingleOrDefault(p => p.PlayerId == stp.PlayerId);
            var team = _db.Teams.SingleOrDefault(t => t.TeamId == stp.TeamId);
            var season = _db.Seasons.SingleOrDefault(s => s.SeasonId == stp.SeasonId);

            dbStp.Player = player;
            dbStp.Team = team;
            dbStp.Season = season;

            _db.SaveChanges();

            return RedirectToAction("ManageSTP");
        }


        public ActionResult ManageLicences()
        {
            var players = _db.Players.Include("Licence").ToList();

            return View(players);
        }

        public ActionResult ExtendLicence(int id)
        {
            var licence = _db.Licences.SingleOrDefault(l => l.LicenceId == id);
            var seasons = _db.Seasons.ToList();
            List<SelectListItem> seasonSelect = new List<SelectListItem>();
            foreach (var s in seasons)
            {
                seasonSelect.Add(new SelectListItem { Text = s.SeasonName, Value = s.SeasonId.ToString() });
            }

            ViewBag.seasonSelect = seasonSelect;

            return View(licence);
        }

        [HttpPost]
        public ActionResult ExtendLicence(Licence licence)
        {
            var season = _db.Seasons.SingleOrDefault(s => s.SeasonId == licence.SeasonExpId);
            var dbLicence = _db.Licences.SingleOrDefault(l => l.LicenceId == licence.LicenceId);
            dbLicence.SeasonExp = season;
            _db.SaveChanges();



            return RedirectToAction("ManageLicences");
        }

    }
}
